package com.example.baseutils;

import android.util.Log;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String工具
 */
public class StringTool {

    /**
     * 查询指定字符串出现的次数
     */
    public static int getStrCunt(String mainStr, String subStr) {
        // 声明一个要返回的变量
        int count = 0;
        // 声明一个初始的下标，从初始位置开始查找
        int index = 0;
        // 获取主数据的长度
        int mainStrLength = mainStr.length();
        // 获取要查找的数据长度
        int subStrLength = subStr.length();
        // 如果要查找的数据长度大于主数据的长度则返回0
        if (subStrLength > mainStrLength) return 0;
        // 循环使用indexOf查找出现的下标，如果出现一次则count++
        while ((index = mainStr.indexOf(subStr, index)) != -1) {
            count++;
            // 从找到的位置下标加上要查找的字符串长度，让指针往后移动继续查找
            index += subStrLength;
        }
        return count;
    }

    /**
     * 通过uid转换为RFid
     *
     * @param data
     * @return
     */
    public static BigInteger getRfid(String data) {
        StringBuffer stringBuffer = new StringBuffer();

        for (int i = 0; i < data.length(); ) {
            int end = i + 2;
            stringBuffer.insert(0, data.substring(i, end));
            i = end;
        }
        String s = new String(stringBuffer);
        //System.out.println(Integer.parseInt(s, 16));
        BigInteger bigInteger = new BigInteger(s.trim(), 16);
        return bigInteger;
    }
    /**
     * 定制班牌转换
     */
    public static String byteHexToString2(byte[] data) {
        String str = byteHexToSting(data);
        //截取有用的一段
        str = str.substring(0, str.indexOf("d0"));
        Log.i("byteHexToString2", str);
        str = hexStr2Str(str);
        Log.i("byteHexToString2....", str);
        return str;
    }

    public static String byteHexToSting(byte[] data) {
        if (data == null) {
            return null;
        }
        StringBuilder stringBuffer = new StringBuilder();
        for (int aR_data : data) {
            //            stringBuffer.append(Integer.toHexString(aR_data & 0x00ff));
            stringBuffer.append(String.format("%02x", aR_data & 0x00ff));
        }
        return stringBuffer.toString();
    }

    /**
     * 取掉高低位算法之后的Hex首尾的零，避免转换十进制的时候干扰
     */
    public static String removeHexZero(String hex) {
        for (int i = 0; i < hex.length(); i++) {
            //如果尾部为零
            if (hex.substring(hex.length() - 1, hex.length()).equals("0")) {
                hex = hex.substring(0, hex.length() - 1);
                return removeHexZero(hex);
            }
            //如果头部是0
            else if (hex.substring(0, 1).equals("0")) {
                hex = hex.substring(1, hex.length());
                return removeHexZero(hex);
            }


        }
        return hex;
    }

    /**
     * 高低算法
     */
    public static String hdHex(String hex) {
        String hexex[] = new String[hex.length() / 2];
        String newHex = "";
        //8057204A
        //4A205780
        for (int i = 0; i < hex.length() / 2; i++) {
            String temstr = hex.substring(hex.length() - 2 - i * 2, hex.length() - i * 2);
            hexex[i] = temstr;
//            System.out.println("temstr  "+temstr);
        }
        for (String s : hexex) {
            newHex = newHex + s;
        }
//        System.out.println( "newHex: "+newHex);
        return newHex;

    }

    public static boolean isHexStrValid(String str) {
        String pattern = "^[0-9A-F]+$";
        return Pattern.compile(pattern).matcher(str).matches();
    }

    /**
     * byte[]转变为16进制String字符, 每个字节2位, 不足补0
     */
    public static String getStringByBytes(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        String result = null;
        String hex = null;
        if (bytes != null && bytes.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(bytes.length);
            for (byte byteChar : bytes) {
                hex = Integer.toHexString(byteChar & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                stringBuilder.append(hex.toUpperCase());
            }
            result = stringBuilder.toString();
        }
        return result;
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    public static byte[] urlStringToBytes(String urlString) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < urlString.length(); ) {
            if (urlString.charAt(i) == '%') {
                if ((i + 2) < urlString.length()) {
                    stringBuilder.append(urlString.substring(i + 1, i + 3));
                }
                i += 3;
            } else {
                stringBuilder.append(String.format("%02x", urlString.charAt(i) & 0xff));
                i++;
            }
        }

        return hexStringToBytes(stringBuilder.toString());
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEFabcdef".indexOf(c);
    }


    /**
     * 判断是否为网址
     */
    public static boolean isHttpUrl(String urls) {
        boolean isurl = false;
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";//设置正则表达式

        String regex2 = "[a-zA-z]+://[^\\s]*";
        Pattern pat = Pattern.compile(regex2.trim());//对比
        Matcher mat = pat.matcher(urls.trim());
        isurl = mat.matches();//判断是否匹配
        if (isurl) {
            isurl = true;
        }
        return isurl;
    }


    private static boolean isBlank(String value) {
        if (value == null || "".equals(value.trim())) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否是16进制数
     *
     * @param strHex
     * @return
     */
    public static boolean isHex(String strHex) {
        int i = 0;
        if (strHex.length() > 2) {
            if (strHex.charAt(0) == '0' && (strHex.charAt(1) == 'X' || strHex.charAt(1) == 'x')) {
                i = 2;
            }
        }
        for (; i < strHex.length(); ++i) {
            char ch = strHex.charAt(i);
            if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
                continue;
            return false;
        }
        return true;
    }

    /**
     * 计算16进制对应的数值
     *
     * @param ch
     * @return
     * @throws Exception
     */
    private static int getHex(char ch) throws Exception {
        if (ch >= '0' && ch <= '9')
            return (int) (ch - '0');
        if (ch >= 'a' && ch <= 'f')
            return (int) (ch - 'a' + 10);
        if (ch >= 'A' && ch <= 'F')
            return (int) (ch - 'A' + 10);
        throw new Exception("error param");
    }

    /**
     * 计算幂
     *
     * @param nValue
     * @param nCount
     * @return
     * @throws Exception
     */
    private static long getPower(int nValue, int nCount) throws Exception {
        if (nCount < 0)
            throw new Exception("nCount can't small than 1!");
        if (nCount == 0)
            return 1;
        long nSum = 1;
        for (int i = 0; i < nCount; ++i) {
            nSum = nSum * nValue;
        }
        return nSum;
    }

    /**
     * 16进制转10进制，对16进制数的每一位数乘以其对应的16的幂，相加。
     *
     * @param strHex 待转换的字符串
     * @param force  是否强制按16进制转换，纯数字也可能是16进制，true则将纯数字按16进制处理
     * @return
     */
    public static long hexToLong(String strHex, boolean force) {
        long nResult = 0;
        String regex = "^\\d{1,}$";
        if (!isBlank(strHex)) {
            strHex = strHex.trim();
        } else {
            return nResult;
        }
        if (!force && strHex.matches(regex)) {
            return Long.parseLong(strHex);
        }
        if (!isHex(strHex)) {
            return nResult;
        }
        String str = strHex.toUpperCase();
        if (str.length() > 2) {
            if (str.charAt(0) == '0' && str.charAt(1) == 'X') {
                str = str.substring(2);
            }
        }
        int nLen = str.length();
        for (int i = 0; i < nLen; ++i) {
            char ch = str.charAt(nLen - i - 1);
            try {
                nResult += (getHex(ch) * getPower(16, i));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return nResult;
    }

    /**
     * 16进制转10进制
     *
     * @param strHex
     * @return
     */
    public static long hexToLong(String strHex) {
        return hexToLong(strHex, true);
    }

    public static String hexToTen(String strHex) {
        long hexToLong = hexToLong(strHex, true);
        return String.valueOf(hexToLong);
    }


    /**
     * 十进制转十六进制
     */
    public static String longToHex(Long str) {
        return Long.toHexString(str);
    }


    /*向左补齐0*/
    public static String padLeft(String s, int length) {
        byte[] bs = new byte[length];
        byte[] ss = s.getBytes();
        Arrays.fill(bs, (byte) (48 & 0xff));
        System.arraycopy(ss, 0, bs, length - ss.length, ss.length);
        return new String(bs);
    }

    /**
     * 16进制转2进制
     */
    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000"
                    + Integer.toBinaryString(Integer.parseInt(hexString
                    .substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }

    /*byte 转换为hex*/
    public static final String byte2hex(byte b[], int len) {
        if (b == null) {
            throw new IllegalArgumentException(
                    "Argument b ( byte array ) is null! ");
        }
        String hs = "";
        String stmp = "";
        for (int n = 0; n < len; n++) {
            stmp = Integer.toHexString(b[n] & 0xff);
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    /**
     *  
     *  * 字节数组转16进制 
     *  * @param bytes 需要转换的byte数组 
     *  * @return  转换后的Hex字符串 
     *  
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     *  
     *  * 字节转十六进制 
     *  * @param b 需要进行转换的byte字节 
     *  * @return  转换后的Hex字符串 
     *  
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }
    /**
     * 16进制直接转换成为字符串(无需Unicode解码)
     *
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }
}
